package cc.yugu.yhdw.webserver.service.basic;


import cc.yugu.yhdw.common.constant.Constant;
import cc.yugu.yhdw.common.domain.basic.UpgradePack;
import cc.yugu.yhdw.common.entity.json.ExtResult;
import cc.yugu.yhdw.common.entity.pagination.Page;
import cc.yugu.yhdw.common.utils.YhdwUtils;
import cc.yugu.yhdw.webserver.config.AppConfig;
import cc.yugu.yhdw.webserver.persistence.basic.UpgradePackMapper;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.Date;
/**
 * 手机端升级业务
 * 
 * @Date:Created in 2018/7/5 15:40
 * @Author:
 * @Modified By: zjn 2018/7/5 15:40
 */ 
@Service
public class UpgradePackService {
    @Autowired
    UpgradePackMapper upgradePackMapper;
    @Autowired
    AppConfig appConfig;

    public UpgradePack find(int id) {
        return upgradePackMapper.find(id);
    }
    /**
    * 分页查询
    * 
    * @Param: [search]
    * @Return: cc.yugu.yhdw.common.entity.pagination.Page
    * @Author By: zjn 2018/7/5  15:40
    */ 
    public Page findPage(UpgradePack search) {
        Page page = search.buildPage();
        page.setTotalItems(upgradePackMapper.findPageCount(search));
        search.setBeginIndex(page.getOffset());
        page.setResult(upgradePackMapper.findPageResult(search));
        return page;
    }
    /**
    * 更新
    * 
    * @Param: [entity]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/5  15:40
    */ 
    public ExtResult update(UpgradePack entity) throws IOException {
        UpgradePack upgradePack = upgradePackMapper.find(entity.getId());
        if(upgradePack == null) {
            return ExtResult.failResult("记录不存在");
        }
        // 得到新文件
        File descFile = appConfig.getFile(upgradePack.getDescFile());
        YhdwUtils.makeParentDir(descFile);
        FileUtils.writeStringToFile(descFile, entity.getVersion(), Constant.ENCODING_UTF_8);
        entity.setUpdateTime(new Date());
        upgradePackMapper.update(entity);

        return ExtResult.successResult();
    }
    /**
    * 更新iOS
    * 
    * @Param: [entity]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/5  15:45
    */ 
    public ExtResult updateIos(UpgradePack entity) {
        entity.setUpdateTime(new Date());
        // 根据主键更新
        upgradePackMapper.update(entity);
        return ExtResult.successResult();
    }
    /**
    * 根据主键删除
    *
    * @Param: [id]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/5  15:46
    */
    public ExtResult delete(int id)  {
        int total = upgradePackMapper.delete(id);
        if (total==0){
            return ExtResult.failResult("删除失败");
        }
        return ExtResult.successResult();
    }
}
